<?php

namespace app\data\controller\api\auth;

use app\data\controller\api\Auth;
use app\data\controller\api\Sendsms;
use app\data\model\BaseUserPayment;
use app\data\model\DataUser;
use app\data\model\DataUserAddress;
use app\data\model\NotarizedMattersModel;
use app\data\model\NotarizedTypeModel;
use app\data\model\ShopOrder;
use app\data\model\ShopOrderItem;
use app\data\model\ShopOrderSend;
use app\data\service\ExpressService;
use think\admin\model\SystemConfig;
use app\data\service\OrderService;
use app\data\service\TencentSerice;
use app\data\service\PaymentService;
use app\data\service\QysService;
use app\data\service\UserAdminService;
use think\admin\extend\CodeExtend;
use think\admin\model\SystemUser;
use think\Exception;
use think\exception\HttpResponseException;

require_once './vendor/TLSSigAPIv2.php';
/**
 * 用户订单数据接口
 * Class Order
 * @package app\data\controller\api\auth
 */
class Order extends Auth
{
    /**
     * 控制器初始化
     */
    protected function initialize()
    {
        parent::initialize();
        if (empty($this->user['status'])) {
            $this->error('账户已被冻结，不能操作订单数据哦！');
        }
    }

    //获取公证类型
    public function gettype()
    {
        $notarial_office_id = input('notarial_office_id',0);//公证处id
        $data = NotarizedTypeModel::mk()->field('id,name')->where(['notarial_office_id'=>$notarial_office_id])->select();
        $this->success('获取公证类型数据成功！', $data);
    }

    /**
     * 获取订单列表
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function get()
    {
        if ($this->request->isPost()) {
            $order_no = input('order_no');
            $where = [];
            if (empty($order_no)){
                $order_status = input('order_status',0); //订单状态(0进行中,1已完成)
                if ($order_status==1) {
                    $where[] = ['status','=',8];
                } else if($order_status==0){
                    $where[] = ['status','<>',8];
                }
            }else{
                $where[] = ['order_no','=',$order_no];
            }
            $user = DataUser::field('id,phone')->where('id',$this->uuid)->find();
            $where[] = ['client_phone','=',$user['phone']];
            $where[] = ['deleted_status','=',0];

            // echo json_encode($where);die();

            $query = ShopOrder::mQuery()->in('status')->equal('order_no');
            $field = 'id,order_no,base_type,matter_id,client_name,client_phone,create_at,status,payment_status,reason_for_rejection,notarial_office_id,number_goods,amount_real,create_type,
            client_id_number,
            unified_numbering,proxy_type';
            // client_id_number,
            $append = ['status_text','type_text','matter_name','notarial_office_name'];
            $result = $query->field($field)->append($append)->where($where)->order('id desc')->page(false, false);
          
            foreach($result['list'] as $k=>$v){
               $data =  QysService::mkPageTicket($v['id']);
               $result['list'][$k]['qys_ticket'] = $data[2]['ticket'];
               $result['list'][$k]['qys_message'] = $data[2]['str'];
            }
            $this->success('获取订单数据成功！', $result);
        }
    }

    public function getorderusermsg()
    {
        if ($this->request->isPost()) {
            $id = input('id');
            $main_data = ShopOrder::mk()->field('client_name,client_id_number,proxy_type')->where(['id'=>$id])->find();
            $this->success('获取订单数据成功！', $main_data);
        }
    }

    /**
     * 用户创建订单
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function addOrder()
    {
        if ($this->request->isPost()) {
            $data = input('');
            $data['uuid'] = $this->uuid;
            $data['unified_numbering'] = OrderService::setOrderNo(); //统一编号
            // 获取随机公证员
            // $data['system_user_id'] = OrderService::getNotary($data['notarial_office_id']);
            // if (empty($data['system_user_id'])) $this->error('未匹配到公证员,请重新选择!');
            $addArray = [];
            foreach ($data['notary_info'] as $k => $v) {
                $addArray[$k]['order_no'] = OrderService::setOrderNo(); //订单号
                $addArray[$k]['base_type'] = $v['base_type'];
                $addArray[$k]['number_goods'] = $v['quantity'];
                $notarizedMattersInfo = NotarizedMattersModel::field('id,name,initial_amount,continued_amount')->where('id',$v['base_type'])->find();//公证事项信息
                if ($v['quantity'] > 1) {
                    $addArray[$k]['amount_real'] = $notarizedMattersInfo['initial_amount'] + ($v['quantity'] - 1) * $notarizedMattersInfo['continued_amount']; //订单实际金额
                } else {
                    $addArray[$k]['amount_real'] = $notarizedMattersInfo['initial_amount']; //订单实际金额
                }

            }
            unset($data['notary_info']);
            foreach ($addArray as $k=>$v) {
                $arr[] = array_merge($v, $data);
            }
            if (ShopOrder::mk()->saveAll($arr)) {
                $this->success('订单添加成功');
            } else {
                $this->error('订单添加失败');
            }
            ShopOrder::mk()->create($data);
        }
    }


    /**
     * 用户创建订单
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $token = $this->request->header('api-token');
            $data = input('');
            // var_dump($data['client_house_purchase_agreement']);die;
            // var_dump($_POST);die;
            if (empty($token)) $this->error('登录认证不能为空！');
            if (empty($data['notarial_office_id'])) $this->error('请选择公证处');
            // if (empty($data['matter_id'])) $this->error('请选择公证类型');
            if (empty($data['client_number'])) $this->error('请添加委托人');
            $data['matter_id'] = intval($data['matter_id']);
            $data['uuid'] = $this->uuid;
            // 获取随机公证员
            // $data['system_user_id'] = OrderService::getNotary($data['notarial_office_id']);
            // if (empty($data['system_user_id'])) $this->error('未匹配到公证员,请重新选择!');


            //公证处
            $where[] = ['notarial_office_id','=',$data['notarial_office_id']];
            //委托类型
            $where[] = ['type','=',$data['base_type']];

            $notarizedMattersInfo = NotarizedMattersModel::field('id,name,initial_amount,continued_amount')->where($where)->find();//公证事项信息
            if (empty($notarizedMattersInfo)){
                $this->error('订单添加失败');
            }
            // 委托人数
            // if ($data['client_number'] > 1) {
            //多人委托
            if ($data['base_type']==0) {
                $id = $data['id'];
                $addArray = [];
                if (isset($data['client_list'])){
                    $data['client_list'] = json_decode($data['client_list'],true);
                }else{
                    $data['client_list'] = [];
                }



                $data['client_number'] = count($data['client_list']);
                //委托人数组
                $first = true;
                $unified_numbering = OrderService::setOrderNo();
                foreach ($data['client_list'] as $k => $v) {
                    if ($first){
                        $addArray[$k]['is_creater'] = 1;
                    }else{
                        $addArray[$k]['is_creater'] = 0;
                    }
                    $addArray[$k]['client_num'] = $k;
                    $addArray[$k]['unified_numbering'] = $unified_numbering;
                    $addArray[$k]['client_name'] = $v['full_name'];//委托人姓名
                    $addArray[$k]['client_phone'] = $v['phone_number'];//委托人联系电话
                    // echo json_encode($v);die;
                    if (isset($v['image_src']) && isset($v['image_src']['idCard_z'])){
                        $addArray[$k]['client_front_of_id_card'] = $v['image_src']['idCard_z'];//委托人身份证正面
                    }else{
                        $addArray[$k]['client_front_of_id_card'] = $v['idCard_z'];
                    }
                    if (isset($v['image_src']) && isset($v['image_src']['idCard_f'])){
                        $addArray[$k]['client_reverse_side_of_id_card'] = $v['image_src']['idCard_f'];//委托人身份证正面
                    }else{
                        $addArray[$k]['client_reverse_side_of_id_card'] = $v['idCard_f'];
                    }

                     if (isset($v['image_src']) && isset($v['image_src']['household_files'])){
                        $addArray[$k]['client_household_register'] = implode(',',$v['image_src']['household_files']);//委托人户口本
                    }else{
                        $addArray[$k]['client_household_register'] = implode(',',$v['household_files']);
                    }



                    $addArray[$k]['order_no'] = OrderService::setOrderNo(); //订单号

                    // 调取身份证识别方法
                    $id_card_info = TencentSerice::distinguish($addArray[$k]['client_front_of_id_card']);
                    $addArray[$k]['client_id_number'] = $id_card_info['IdNum'];//身份证号
                    $addArray[$k]['client_birthday'] = $id_card_info['Birth'];//出生日期
                    $addArray[$k]['client_sex'] = $id_card_info['Sex'];

                    $order_no[] = OrderService::setOrderNo();
                    if ($data['number_goods'] > 1) {
                        $data['amount_real'] = $notarizedMattersInfo['initial_amount'] + ($data['number_goods'] - 1) * $notarizedMattersInfo['continued_amount']; //订单实际金额
                    } else {
                        $data['amount_real'] = $notarizedMattersInfo['initial_amount']; //订单实际金额
                    }
                    $first = false;
                }
                $clientArray = $data['client_list'];
                unset($data['client_list']);

                $data['trustee_list'] = json_decode($data['trustee_list'],true);
                $data['trustee_number'] = count($data['trustee_list']);

                $trusteeArray = [];
                $trusteemsgArray = [];

                //受托人数组
                foreach ($data['trustee_list'] as $k => $v) {
                    if(isset($v['image_src']['idCard_z'])){
                        $trusteeArray[$k]['idCard_z'] = $v['image_src']['idCard_z'];
                    }else{
                        $trusteeArray[$k]['idCard_z'] = $v['idCard_z'];
                    }
                    if(isset($v['image_src']['idCard_f'])){
                        $trusteeArray[$k]['idCard_f'] = $v['image_src']['idCard_f'];
                    }else{
                        $trusteeArray[$k]['idCard_f'] = $v['idCard_f'];
                    }
                    // 调取身份证识别方法
                    $id_card_info = TencentSerice::distinguish($trusteeArray[$k]['idCard_z']);
                    $trusteemsgArray[$k]['client_name'] = $id_card_info['Name'];//身份证号
                    $trusteemsgArray[$k]['client_id_number'] = $id_card_info['IdNum'];//身份证号
                    $trusteemsgArray[$k]['client_birthday'] = $id_card_info['Birth'];//出生日期
                    $trusteemsgArray[$k]['client_sex'] = $id_card_info['Sex'];
                }
                unset($data['client_list']);

                $data['trustee_id_card'] = json_encode($trusteeArray);
                $data['trustee_msg'] = json_encode($trusteemsgArray);

                foreach ($clientArray as $k => $v) {
                    if (isset($v['image_src']['idCard_z'])){
                        $clientArray[$k]['idCard_z'] = $v['image_src']['idCard_z'];
                    }else{
                        $clientArray[$k]['idCard_z'] = $v['idCard_z'];
                    }
                    if (isset($v['image_src']['idCard_f'])){
                        $clientArray[$k]['idCard_f'] = $v['image_src']['idCard_f'];
                    }else{
                        $clientArray[$k]['idCard_f'] = $v['idCard_f'];
                    }
                    if (isset($v['image_src']['household_files'])){
                        $clientArray[$k]['household_files'] = $v['image_src']['household_files'];
                    }else{
                        $clientArray[$k]['household_files'] = $v['household_files'];
                    }
                }
                $data['client_json'] = json_encode($clientArray);
                //离婚协议
                // $data['client_divorce_agreement'] = json_encode($data['client_divorce_agreement']);
                //其他
                // $data['other'] = json_encode($data['other']);
                //状态 信息确认中
                $data['status'] = 1;
                //已经支付
                // $data['payment_status'] = 1;

                unset($data['id']);
                foreach ($addArray as $k=>$v) {
                    $arr[] = array_merge($v, $data);
                }
                // 同一訂單號
                // echo json_encode($arr);die;
                // 大于0 修改 0 新增
                if ($id == 0){
                    if (ShopOrder::mk()->saveAll($arr)) {
                        $this->success('订单添加成功', ['id' => $id]);
                    } else {
                        $this->error('订单添加失败');
                    }
                }
                //修改
                else{
                    try {
                        $main_data = ShopOrder::mk()->where(['id'=>$id])->find();
                        $unified_numbering = $main_data['unified_numbering'];
                        ShopOrder::mk()->where(['unified_numbering'=>$unified_numbering])->select()->each(function ($data,$key) use($arr){
                            // var_dump($arr[$key]);die;
                            unset($arr[$key]['id']);
                            ShopOrder::mk()->strict(false)->where(['id'=>$data['id']])->update($arr[$key]);
                        });
                        $this->success('订单修改成功', ['order_no' => $order_no]);
                    }catch (Exception $e){
                        $this->error('订单修改失败');
                    }
                }

            } else {
                $data['order_no'] = OrderService::setOrderNo();
                $data['unified_numbering'] = $data['order_no'];
                //订单实际金额
                $data['amount_real'] = $notarizedMattersInfo['initial_amount'];
                if ($data['number_goods'] > 1) {
                    $data['amount_real'] = $notarizedMattersInfo['initial_amount'] + ($data['number_goods'] - 1) * $notarizedMattersInfo['continued_amount']; //订单实际金额
                }

                // 调取身份证识别方法
                $id_card_info = TencentSerice::distinguish($data['client_front_of_id_card']);
                $data['client_id_number'] = $id_card_info['IdNum'];//身份证号
                $data['client_birthday'] = $id_card_info['Birth'];//出生日期
                $data['client_sex'] = $id_card_info['Sex'];


                //调取身份证识别方法
                //代理人信息



                //状态 信息确认中
                $data['status'] = 1;
                //已经支付
                // $data['payment_status'] = 1;

                $data = array_filter($data,function($v){
                    return $v != 'undefined';
                });

                // 大于0 修改 0 新增
                if ($data['id'] == 0){
                    $id = ShopOrder::mk()->insertGetId($data);
                    if ($id) {
                        $this->success('订单添加成功', ['id' => $id,'order_no' => $data['order_no']]);
                    } else {
                        $this->error('订单添加失败');
                    }
                }else{
                    $id = $data['id'];
                    unset($data['id']);
                    if (ShopOrder::mk()->where(['id'=>$id])->update($data)) {
                        $this->success('订单修改成功', ['id' => $id,'order_no' => $data['order_no']]);
                    } else {
                        $this->error('订单修改失败');
                    }
                }

            }
        }
    }

    //获取阅读协议
    public function find_read_agreement()
    {
        if ($this->request->isPost()) {
            $data = input('');
            // var_dump($data);die;
            $id = $data['id'];
            $data = ShopOrder::mk()->field('read_agreement1,read_agreement2,read_agreement3,read_agreement4,read_agreement5')->where(['id'=>$id])->find();
            if (empty($data)){
                $this->error('数据错误');
            }else{
                $this->success('订单添加成功', ['data' => $data]);
            }
        }
    }

    //获取委托书 图片格式
    public function get_proxy_statement_()
    {
        if ($this->request->isPost()) {
            $data = input('');
            $id = $data['id'];
            $sign = isset($data['sign'])?$data['sign']:0;
            if (empty($id)) {
                $this->error('信息错误');
            }
            // var_dump($data);die;
            $main_data = ShopOrder::field('unified_numbering,proxy_statement,handwritten_signature')->where('id',$id)->find();
            if (empty($main_data)){
                $this->error('信息错误1');
            }
            $unified_numbering = $main_data['unified_numbering'];
            // 订单信息
            $order = ShopOrder::field('client_name,create_at')->where('unified_numbering',$unified_numbering)->select()->toArray();
            // 公证书模板
            // $path = SystemConfig::mk()->where('name','template_image')->value('value');
            $path = $main_data['proxy_statement'];

            $image_path = str_ireplace(sysconf('base.site_host'),'.',$path);
            // var_dump($image);die();
            $image = \think\Image::open($image_path);
            $storage_path = './upload/template/'.$unified_numbering.'.png';
            foreach ($order as $K=>$v) {
                $text = '委托人：'.$v['client_name'].'，男，1998年1月1日，身份证号：220382199801011234';
                $locate = [50,130];
                // 如果有多个委托人,则设置每个之间的高度
                if ($K>0) {
                    foreach ($locate as $key=>$value) {
                        $locate[1] = $value + 20;
                    }
                }
                // 设置委托人信息
                $image->text($text,BASE_PATH.'st.ttf',10,'#000000',\think\Image::WATER_NORTHWEST,$locate)->save($storage_path);
            }

            // 设置日期水印
            $image->text($order[0]['create_at'],BASE_PATH.'st.ttf',11,'#000000',\think\Image::WATER_SOUTHEAST,[-100,-100])->save($storage_path);
            $url = config('app.domain').'upload/template/'.$unified_numbering.'.png';
            //需要签名
            if ($sign == 1){
                $handwritten_signature = $main_data['handwritten_signature'];
                //图片合并
                $ext = pathinfo($handwritten_signature);
                $signImg = null;
                //创建图片对象
                switch ($ext['extension']) {
                    case 'jpg':
                        $signImg = imagecreatefromjpeg($handwritten_signature);
                        break;
                    case 'png':
                        $signImg = imagecreatefrompng($handwritten_signature);
                        break;
                    case 'gif':
                        $signImg = imagecreatefromgif($handwritten_signature);
                        break;
                }

                $dst_x = 100;
                $dst_y = 500;
                $back_IMG = imagecreatefrompng($storage_path);
                // var_dump($back_IMG);
                //合成图片
                imagecopymerge($back_IMG, $signImg, $dst_x, $dst_y, 0, 0, imagesx($signImg), imagesy($signImg), 100);
                imagepng($back_IMG, $storage_path);
            }

            $this->success('获取成功',$url);
        }
    }

    //获取委托书文字形式
    public function get_proxy_statement()
    {
        if ($this->request->isPost()) {
            $data = input('');
            $id = $data['id'];
            $sign = isset($data['sign'])?$data['sign']:0;
            if (empty($id)) {
                $this->error('信息错误');
            }
            $main_data = ShopOrder::field('unified_numbering,proxy_statement,handwritten_signature,proxy_type,proxy_title')->where('id',$id)->find();
            if (empty($main_data)){
                $this->error('信息错误1');
            }
            $unified_numbering = $main_data['unified_numbering'];
            $proxy_statement = $main_data['proxy_statement'];
            // 订单信息
            $order = ShopOrder::field('id,client_name,client_sex,client_birthday,client_id_number,create_at,trustee_msg')->where('unified_numbering',$unified_numbering)->select()->toArray();

            $user = [];
            // 'client_name':'李四',
            // 'client_sex':'男',
            // 'client_birthday':'1997年8月25日',
            // 'client_id_number':'211322199409191531',
            //受托人数组
            $user_s = [];
            foreach ($order as $k=>$v) {
                // $text = '委托人：'.$v['client_name'].'，男，1998年1月1日，身份证号：220382199801011234';
                $user[] = [
                    'client_name'=>$v['client_name'],
                    'client_sex'=>$v['client_sex'],
                    'client_birthday'=>date("Y年m月d日",strtotime($v['client_birthday'])),
                    'client_id_number'=>$v['client_id_number'],
                ];
                if ($k == 0){
                    $trustee_msg = json_decode($v['trustee_msg'],true);
                    if (!empty($trustee_msg)){
                        foreach($trustee_msg as $key => $value){
                            $trustee_msg[$key]['client_birthday'] = date("Y年m月d日",strtotime($trustee_msg[$key]['client_birthday']));
                        }

                        $user_s = $trustee_msg;
                    }
                }
            }



            $create_at = $order[0]['create_at'];
            //需要签名
            $handwritten_signature = '';
            if ($sign == 1){
                $handwritten_signature = $main_data['handwritten_signature'];
            }

            $rt = [];
            $rt['user'] = $user;
            $rt['user_s'] = $user_s;
            $rt['create_at'] = date("Y年m月d日",strtotime($create_at));
            $rt['sign_img_src'] = $handwritten_signature;
            $rt['proxy_type'] = $main_data['proxy_type'];
            $rt['proxy_title'] = $main_data['proxy_title'];
            $rt['html'] = $proxy_statement;
            $this->success('获取成功',$rt);
        }
    }

    //认证
    public function authentication()
    {
        if ($this->request->isPost()) {
            //签名 和 id
            $data = input('');
            $id = $data['id'];
            $sign_img = $data['sign_img'];
            $main_data = ShopOrder::mk()->where(['id'=>$id])->find();
            if (empty($main_data)){
                $this->error('数据错误');
            }
            $video_forensics = $main_data['video_forensics'];
            // 订单流程状态(0已取消,1信息确认中,2信息有误,3待认证,4认证审核中,5认证通过,6认证失败,7审批人审核,8已完成)
            if ($video_forensics == 0){
                $status = 5;
            }
            //需要视频认证
            else{
                $status = 4;

            }
            ShopOrder::mk()->where(['id'=>$id])->update(
                [
                    'handwritten_signature'=>$sign_img,
                    //认证审核通过
                    'status'=>$status,
                ]
            );
            if ($status == 4){
            	//短信提示待视频认证
				$url_link = getwxlink($id,1);

				//获取变量
				$res = substr($url_link, strripos($url_link, "?t=") + 3);
				//发送短信
				$m = new Sendsms();

				$client_phone = ShopOrder::mk()->where(['id'=>$id])->value('client_phone');
				$phone = $client_phone;
				$SecretId = sysconf('vx.secretId');
				$SecretKey = sysconf('vx.secretKey');

				$templateid = '1625713';

				$post_data = [
					$res
				];
				$rt = $m->Sms_status($phone, $SecretId, $SecretKey,$templateid,$post_data);
            }
            $this->success('认证审核通过');
        }
    }

    /**
     * 获取支付支付数据
     */
    public function channel()
    {
        $data = $this->_vali(['uuid.value' => $this->uuid, 'order_no.require' => '单号不能为空']);
        $payments = ShopOrder::mk()->where($data)->value('payment_allow');
        if (empty($payments)) $this->error('获取订单支付参数失败');
        // 读取支付通道配置
        $query = BaseUserPayment::mk()->where(['status' => 1, 'deleted' => 0]);
        $query->whereIn('code', str2arr($payments))->whereIn('type', PaymentService::getTypeApi($this->type));
        $result = $query->order('sort desc,id desc')->column('type,code,name,cover,content,remark', 'code');
        foreach ($result as &$vo) $vo['content'] = ['voucher_qrcode' => json_decode($vo['content'])->voucher_qrcode ?? ''];
        $this->success('获取支付参数数据', array_values($result));
    }

    /**
     * 获取订单支付状态
     * @throws \think\db\exception\DbException
     */
    public function payment()
    {
        $data = $this->_vali([
            'uuid.value'            => $this->uuid,
            'order_no.require'      => '单号不能为空',
            'order_remark.default'  => '',
            'payment_code.require'  => '支付不能为空',
            'payment_back.default'  => '', # 支付回跳地址
            'payment_image.default' => '', # 支付凭证图片
        ]);
        [$map, $order] = $this->getOrderData();
        if ($order['status'] !== 2) $this->error('不能发起支付');
        if ($order['payment_status'] > 0) $this->error('已经完成支付');
        // 更新订单备注
        if (!empty($data['order_remark'])) {
            ShopOrder::mk()->where($map)->update([
                'order_remark' => $data['order_remark'],
            ]);
        }
        // 自动处理用户字段
        $openid = '';
        if (in_array($this->type, [UserAdminService::API_TYPE_WXAPP, UserAdminService::API_TYPE_WECHAT])) {
            $openid = $this->user[UserAdminService::TYPES[$this->type]['auth']] ?? '';
            if (empty($openid)) $this->error("发起支付失败");
        }
        try {
            // 返回订单数据及支付发起参数
            $type = $order['amount_real'] <= 0 ? 'empty' : $data['payment_code'];
            $param = PaymentService::instance($type)->create($openid, $order['order_no'], $order['amount_real'], '商城订单支付', '', $data['payment_back'], $data['payment_image']);
            $this->success('获取支付参数', ['order' => ShopOrder::mk()->where($map)->find() ?: new \stdClass(), 'param' => $param]);
        } catch (HttpResponseException $exception) {
            throw $exception;
        } catch (\Exception $exception) {
            $this->error($exception->getMessage());
        }
    }

    /**
     * 获取输入订单
     * @return array [map, order]
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    private function getOrderData(): array
    {
        $map = $this->_vali([
            'uuid.value'       => $this->uuid,
            'order_no.require' => '单号不能为空',
        ]);
        $order = ShopOrder::mk()->where($map)->find();
        if (empty($order)) $this->error('读取订单失败');
        return [$map, $order];
    }

    /**
     * 获取信息资料
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getInformation()
    {
        $data = $this->_vali([
            'uuid.value' => $this->uuid,
            'id.require' => 'id不能为空', //订单主键id
        ]);
        // $field = 'id,matter_id,client_name,client_phone,client_front_of_id_card,client_reverse_side_of_id_card,client_household_register,client_marital_status,client_marriage_certificate,client_divorce_certificate,client_divorce_agreement,client_property_ownership_certificate,client_house_purchase_agreement,client_property_information,trustee_number,front_of_fathers_id_card,reverse_side_of_fathers_id_card,front_of_mothers_id_card,reverse_side_of_mothers_id_card,parents_household_register,other,proof_of_relationship';
        $field = '*';
        $append = ['matter_name'];
        $info = ShopOrder::field($field)->append($append)->where('id',$data['id'])->find();
        $info['client_json'] = json_decode($info['client_json'],true);
        if (empty($info['client_divorce_agreement'])){
            $info['client_divorce_agreement'] = [];
        }else{
            $info['client_divorce_agreement'] = explode(",",$info['client_divorce_agreement']);

        }




        if (empty($info['client_household_register'])){
            $info['client_household_register'] = [];
        }else{
            $info['client_household_register'] = explode(",",$info['client_household_register']);
        }

        if (empty($info['parents_household_register'])){
            $info['parents_household_register'] = [];
        }else{
            $info['parents_household_register'] = explode(",",$info['parents_household_register']);
        }

        if (empty($info['proof_of_relationship'])){
            $info['proof_of_relationship'] = [];
        }else{
            $info['proof_of_relationship'] = explode(",",$info['proof_of_relationship']);
        }

        if (empty($info['client_marriage_certificate'])){
            $info['client_marriage_certificate'] = [];
        }else{
            $info['client_marriage_certificate'] = explode(",",$info['client_marriage_certificate']);
        }

        if (empty($info['client_divorce_certificate'])){
            $info['client_divorce_certificate'] = [];
        }else{
            $info['client_divorce_certificate'] = explode(",",$info['client_divorce_certificate']);
        }




        if (empty($info['client_house_purchase_agreement'])){
            $info['client_house_purchase_agreement'] = [];
        }else{
            $info['client_house_purchase_agreement'] = explode(",",$info['client_house_purchase_agreement']);
        }
        if (empty($info['client_property_information'])){
            $info['client_property_information'] = [];
        }else{
            $info['client_property_information'] = explode(",",$info['client_property_information']);
        }
        $info['trustee_id_card'] = json_decode($info['trustee_id_card'],true);
        if (empty($info['trustee_id_card'])){
            $info['trustee_id_card'] = [];
        }
        if (empty($info['other'])){
            $info['other'] = [];
        }else{
            $info['other'] = explode(",",$info['other']);
        }

        //房产证
        if (empty($info['client_property_ownership_certificate'])){
            $info['client_property_ownership_certificate'] = [];
        }else{
            $info['client_property_ownership_certificate'] = explode(",",$info['client_property_ownership_certificate']);
        }

        // 1未婚2已婚3离异  數據庫 0未婚,1已婚,2离异
        $info['client_marital_status'] = $info['client_marital_status']+1;
        if ($info) {
            $this->success('获取成功', $info);
        } else {
            $this->error('获取失败');
        }
    }


    public function getxieyi()
    {
        $id = input('id','');
        if ($id==0) {
            $this->error('信息错误');
        }
        $order = ShopOrder::field('handwritten_signature,read_agreement1,read_agreement2,read_agreement3,read_agreement4,read_agreement5,create_at')->where('id',$id)->find()->toArray();
        $rt['handwritten_signature'] = $order['handwritten_signature'];
        $rt['read_agreement1'] = $order['read_agreement1'];
        $rt['read_agreement2'] = $order['read_agreement2'];
        $rt['read_agreement3'] = $order['read_agreement3'];
        $rt['read_agreement4'] = $order['read_agreement4'];
        $rt['read_agreement5'] = $order['read_agreement5'];
        $rt['create_at'] = date("Y年m月d日",strtotime($order['create_at']));
        // $rt['create_at'] = explode(' ',$order['create_at'])[0];
        $this->success('获取成功',$rt);
    }


    /**
     * 委托书查看
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function powerOfAttorneyViewing()
    {
        $unified_numbering = input('unified_numbering',''); //统一编号
        if (empty($unified_numbering)) {
            $this->error('信息错误');
        }
        // 订单信息
        $order = ShopOrder::field('client_name,create_at')->where('unified_numbering',$unified_numbering)->select()->toArray();
        // 公证书模板
        $path = SystemConfig::mk()->where('name','template_image')->value('value');

        $image = str_ireplace('http://127.0.0.2','.',$path);
        $image = \think\Image::open($image);
        $storage_path = './upload/template/'.$unified_numbering.'.png';
        foreach ($order as $K=>$v) {
            $text = '委托人：'.$v['client_name'].'，男，1998年1月1日，身份证号：220382199801011234';
            $locate = [120,180];
            // 如果有多个委托人,则设置每个之间的高度
            if ($K>0) {
                foreach ($locate as $key=>$value) {
                    $locate[1] = $value + 20;
                }
            }
            // 设置委托人信息
            $image->text($text,BASE_PATH.'st.ttf',10,'#000000',\think\Image::WATER_NORTHWEST,$locate)->save($storage_path);
        }
        // 设置日期水印
        $image->text($order[0]['create_at'],BASE_PATH.'st.ttf',11,'#000000',\think\Image::WATER_SOUTHEAST,[-100,-100])->save($storage_path);
        $url = 'http://127.0.0.2/upload/template/'.$unified_numbering.'.png';
        $this->success('获取成功',$url);
    }
    // 支付
    public function start_payment(){
        $order_no = input('order_no','');
        if (empty($order_no)) {
            $this->error('信息错误');
        }
        $info = ShopOrder::mk()->where('order_no',$order_no)->find();
        if (empty($info)) {
            $this->error('数据信息错误');
        }
       
        // -----------------------------微信支付----------------------------------------------------
        $appid = sysconf('wechat.appid');
        $mch_id = sysconf('wechat.mch_id');
        $mch_key = sysconf('wechat.mch_key');
        $config =[
            'appid'=> $appid,
            'mch_id'=> $mch_id,
            'mch_key'=> $mch_key,
        ];
        $wechat = new \WeChat\Pay($config);
        $uu_id = CodeExtend::uniqidDate(20, 'T');
        $user = $this->getUser();

        $openid = $user['openid1'];

        $msg = '公证费用';
        $notify_url = '/data/api.auth.order/pay';
        $options = [
            'body'             => $msg,
            'out_trade_no'     => $uu_id,
            'total_fee'        => $info['amount_real']*100*1,
            'openid'           => $openid,
            'trade_type'       => 'JSAPI',
            'notify_url'       => request()->domain().$notify_url,// 支付成功回调地址
            'spbill_create_ip' => $this->request->ip(),// 本IP
        ];

        try {
            $money = $options['total_fee'];
            if ($money>0){
                // 生成预支付码
                $result = $wechat->createOrder($options);
                // var_dump($result);
                // return 1;
                // 创建JSAPI参数签名
                $options = $wechat->createParamsForJsApi($result['prepay_id']);
                $options['total_fee'] = $money;
            }
            $options['order_no'] = $order_no;
            $this->success('获取成功',$options);
        } catch (Exception $e) {
            // 出错啦，处理下吧
            echo $e->getMessage() . PHP_EOL;
        }
    }

    //支付订单
    public function pay()
    {
        $order_no = input('order_no','');
        if (empty($order_no)) {
            $this->error('信息错误');
        }
        $info = ShopOrder::mk()->where('order_no',$order_no)->find();
        if (empty($info)) {
            $this->error('数据信息错误');
        }
        $base_type = $info['base_type'];
        $data = [
            'payment_status'=>1,
        ];
        if ($base_type == 0){
            //统一编号
            $unified_numbering = $info['unified_numbering'];
            ShopOrder::mk()->where('unified_numbering',$unified_numbering)->update($data);
        }else{
            ShopOrder::mk()->where('order_no',$order_no)->update($data);
        }
        // 发送短信 获取链接
		//短信提示待视频认证
	    $id = $info['id'];
		$url_link = getwxlink($id,1);

		//获取变量
		$res = substr($url_link, strripos($url_link, "?t=") + 3);
		//发送短信
		$m = new Sendsms();

		$client_phone = ShopOrder::mk()->where(['id'=>$id])->value('client_phone');
		$phone = $client_phone;
		$SecretId = sysconf('vx.secretId');
		$SecretKey = sysconf('vx.secretKey');

		$templateid = '1625714';

		$post_data = [
			$res
		];
		$rt = $m->Sms_status($phone, $SecretId, $SecretKey,$templateid,$post_data);
        $this->success('获取成功',1);
    }

    /*
     * 测试身份证识别
     */
    public function shibie()
    {
        $data = TencentSerice::distinguish('https://gz.024wl.com/upload/87/95e313a7b977f304959cd0d4b28645.jpg');
        $this->success('获取成功',$data);
    }

    //
    public function getSign(){
        $record_id = input('record_id');
        //获取订单的审核员的id
        $system_user_id = ShopOrder::mk()->where(['id'=>$record_id])->value('system_user_id');

        $user = $this->getUser();
        $user_id = $user['phone'];
        $appid  = sysconf('vx.sdkappid');
        $appkey  = sysconf('vx.sdkappkey');
        $api = new \Tencent\TLSSigAPIv2($appid, $appkey);


        //创建自己的即时通讯用户
        //把人注册到通讯中
        $sig = $api->genUserSig('administrator');
        $random = random_int(0,4294967295);
        //实时通讯 导入用户
        $url = "https://console.tim.qq.com/v4/im_open_login_svc/account_import?sdkappid=".$appid."&identifier=administrator&usersig=".$sig."&random=".$random."&contenttype=json";
        $data_string = json_encode(['UserID'=>$user_id,'Nick'=>'','FaceUrl'=>'']);
        $ch = curl_init();
        $timeout = 20;
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        $file_contents = curl_exec($ch);
        curl_close($ch);
        // var_dump($data_string);
        // var_dump($file_contents);
        // return 1;
        $arr = json_decode($file_contents,true);
        if ($arr['ErrorCode'] == '0'){

        }else{
            $this->error('调用接口出错');
        }
        $sig = $api->genUserSig($user_id);
        $rt = [];
        $rt['sdkAppID'] = intval($appid);
        $rt['phone'] = $user_id;
        $rt['system_user_id'] = strval($system_user_id);
        $rt['sign'] = $sig . "\n";
        $this->success('获取成功',$rt);
        // echo $sig . "\n";
    }

    //获取微信登录的手机号
	public function get_phone()
	{
		$code = input('code');
		$appid = sysconf('wechat.appid');
		$secret = sysconf('wechat.appsecret');
		$options = [
			'appid'=>$appid,
			'appsecret'=>$secret
		];
		$result = (new \WeMini\Crypt($options))->getPhoneNumber($code);
		if ($result['errcode']== '0'){
			$phone = $result['phone_info']['purePhoneNumber'];
			//存入数据库
			$user = $this->getUser();
			DataUser::mk()->where(['id'=>$user['id']])->update(['phone'=>$phone]);
			$this->success('成功', $phone);
		}else{
			$this->error('获取手机号失败');
		}

		// $api = new \Tencent\TLSSigAPIv2($appid, $appkey);
	}

	//客户角度: 获取微信双人视频通话参数
	public function getParams(){
        $record_id = input('record_id');
        //获取订单的审核员的id
        $system_user_id = ShopOrder::mk()->where(['id'=>$record_id])->value('system_user_id');

        $user = $this->getUser();

        $nickname = $user['nickname'];
        $headImage = $user['headimg'];
        $openid = $user['openid1'];
        $caller = [
        	'nickname'=>$nickname,
	        'headImage'=>$headImage,
	        'openid'=>$openid,
        ];
        $system_user = SystemUser::mk()->where(['id' => $system_user_id])->find();
        if (!empty($system_user)){
        	$listener = [
				'nickname'=>$system_user['nickname'],
		        'headImage'=>$system_user['headimg'],
		        'openid'=>$system_user['openid1'],
	        ];
        	$data['caller'] = $caller;
        	$data['listener'] = $listener;
        	$this->success('成功', $data);
        }else{
        	$this->error('公证员不存在');
        }
    }
}